package com.learn.word.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.word.bean.ProblemSelectOne;
import com.learn.word.entity.Problem;
import com.learn.word.entity.Word;
import com.learn.word.mapper.ProblemMapper;
import com.learn.word.mapper.WordMapper;
import com.learn.word.service.IProblem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Valley
 * Description
 * Created by Valley on 2023/6/19 20:22
 */
@Service
public class ProblemService extends ServiceImpl<ProblemMapper, Problem> implements IProblem {

    @Autowired
    ProblemMapper problemMapper;
    @Autowired
    WordMapper wordMapper;

    @Override
    public List<ProblemSelectOne> selectList(Long wId) {

        LambdaQueryWrapper<Problem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Problem::getWId, wId);
        List<Problem> list = this.list(wrapper);
        return list.stream()
                .map(problem -> {
                    ProblemSelectOne one = new ProblemSelectOne();
                    one.setTitle(problem.getTitle());
                    one.setTitleCN(problem.getTitleCN());
                    Word word = wordMapper.selectById(problem.getWId());
                    one.setAnswer(word.getWord());
                    one.setAnswerCN(word.getWordCN());
                    List<String> randomChoice = getRandomChoice(word.getId());
                    one.setChoiceA(randomChoice.get(0));
                    one.setChoiceB(randomChoice.get(1));
                    one.setChoiceC(randomChoice.get(2));
                    one.setChoiceD(randomChoice.get(3));
                    return one;
                }).collect(Collectors.toList());
    }

    private List<String> getRandomChoice(Long id){
        List<String> list = new ArrayList<>();
        list.add(wordMapper.selectById(id).getWord());
        int size = wordMapper.selectList(null).size();
        while (list.size() < 3){
            int random = RandomUtil.randomInt(1, size);
            String word = wordMapper.selectById(random).getWord();
            if (!list.contains(word)){
                list.add(word);
            }
        }
        Collections.shuffle(list);
        return list;
    }

}